<template>
  <!-- 数据可视化卡片 -->
  <div class="dashboard-cards">
    <!-- 修改第一个卡片为商品评分柱状图 -->
    <el-card shadow="hover" class="dashboard-card">
      <template #header>
        <div class="card-header">
          <span>商品评分分布分析</span>
        </div>
      </template>
      <div class="chart-container">
        <div ref="ratingChart" style="height: 300px;"></div>
      </div>
    </el-card>

    <el-card shadow="hover" class="dashboard-card">
      <template #header>
        <div class="card-header">
          <span>热销商品TOP10</span>
        </div>
      </template>
      <div class="chart-container">
        <div ref="salesChart" style="height: 300px;"></div>
      </div>
    </el-card>

    <el-card shadow="hover" class="dashboard-card">
      <template #header>
        <div class="card-header">
          <span>库存预警分析</span>
        </div>
      </template>
      <div class="chart-container">
        <div ref="stockChart" style="height: 300px;"></div>
      </div>
    </el-card>

    <el-card shadow="hover" class="dashboard-card">
      <template #header>
        <div class="card-header">
          <span>价格区间分布</span>
        </div>
      </template>
      <div class="chart-container">
        <div ref="priceChart" style="height: 300px;"></div>
      </div>
    </el-card>
  </div>

  <el-dialog
      v-model="dialog.show"
      :title="dialog.title"
      width="450px"
      :close-on-click-modal="false"
  >
    <Dialog
        v-if="dialog.show"
        @getTableData="getTableData"
        v-model:show="dialog.show"
        :id="dialog.id"
        :level="dialog.level"
        :parentId="dialog.parentId"
    ></Dialog>
  </el-dialog>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { copy } from 'copy-anything'
import { reactive, ref, onMounted } from 'vue'
import { get, post } from '@/plugins/axios'
import url from '@/views/MerchandiseM/category/pathUtil'
import { ElMessage, ElMessageBox } from 'element-plus';
import Dialog from '@/views/MerchandiseM/category/dialog'
import * as echarts from 'echarts'; // 引入ECharts

/* -------------------------数据部分------------------------------ */
const tableData = ref([])
const allTableData = ref([])
const params = reactive({})
const formObj = null
const dialog = reactive({
  title: '',
  id: '',
  show: false,
  parentId: null,
  level: null
})
const searchValue = ref('')

// 图表引用
const ratingChart = ref(null)  // 修改为评分图表
const salesChart = ref(null)
const stockChart = ref(null)
const priceChart = ref(null)

// 可视化数据
const goodsData = ref([])
const ratingDistributionData = ref({})  // 存储评分分布数据

/* -------------------------生命周期------------------------------ */
onMounted(() => {
  getRatingDistributionData()  // 获取评分分布数据
  getGoodsData()
})

/* -------------------------函数部分------------------------------ */
// 获取商品数据
function getGoodsData() {
  get('/goods/getList', {}, content => {
    goodsData.value = content
    // 确保评价数据也已加载
    if (goodsData.value.length > 0) {
      initCharts()
    }
  })

}

// // 获取商品评价数据
// function getReviewsData() {
//   // 获取前1000条评价数据（可根据实际数据量调整）
//   get('/goodsReview/page?page=1&size=1000', {productId:1}, content => {
//     reviewsData.value = content.records
//     // 确保商品数据也已加载
//     if (goodsData.value.length > 0) {
//       initCharts()
//     }
//   })
// }

// 初始化图表
function initCharts() {
  // 商品评分分析
  initRatingChart()
  // 热销商品图
  initSalesChart()
  // 库存预警图
  initStockChart()
  // 价格分布图
  initPriceChart()
}

// 获取评分分布数据
function getRatingDistributionData() {
  get('/goodsReview/rating', {},content => {
    ratingDistributionData.value = content
    // 确保商品数据也已加载
    if (ratingDistributionData.value.length > 0) {
      initCharts()
    }
  })
}

// 商品评分分析 - 柱状图
function initRatingChart() {
  if (!ratingChart.value) return;
  const chart = echarts.init(ratingChart.value)

  // 创建商品ID到商品名称的映射
  const goodsMap = {}
  goodsData.value.forEach(good => {
    goodsMap[good.id] = good.name
  })

  // 只处理有评价的商品
  const validGoods = Object.keys(ratingDistributionData.value)
      .map(id => {
        const productId = parseInt(id)
        return {
          id: productId,
          name: goodsMap[productId] || `商品 ${productId}`,
          ratings: ratingDistributionData.value[productId]
        }
      })
      .filter(item => item.name && item.ratings.some(count => count > 0))

  // 按总评价数排序，取前15个商品
  const sortedGoods = [...validGoods].sort((a, b) => {
    const totalA = a.ratings.reduce((sum, count) => sum + count, 0);
    const totalB = b.ratings.reduce((sum, count) => sum + count, 0);
    return totalB - totalA;
  }).slice(0, 15);

  // 准备图表数据
  const seriesData = [];
  const ratingColors = ['#ff4d4f', '#ffa940', '#ffc53d', '#73d13d', '#389e0d'];

  // 为每个评分等级创建一个系列
  for (let i = 0; i < 5; i++) {
    seriesData.push({
      name: `${i+1}星`,
      type: 'bar',
      stack: 'total',
      emphasis: { focus: 'series' },
      itemStyle: { color: ratingColors[i] },
      data: sortedGoods.map(good => good.ratings[i])
    });
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: function(params) {
        const goodIndex = params[0].dataIndex;
        const good = sortedGoods[goodIndex];
        const total = good.ratings.reduce((sum, count) => sum + count, 0);

        let result = `<div style="margin-bottom:5px;font-weight:bold">${good.name}</div>`;

        for (let i = 0; i < 5; i++) {
          const count = good.ratings[i];
          const percent = total > 0 ? ((count / total) * 100).toFixed(1) : 0;
          result += `${i+1}星: ${count} (${percent}%)<br/>`;
        }

        result += `<div style="margin-top:5px;font-weight:bold">总评价: ${total}</div>`;
        return result;
      }
    },
    legend: {
      data: ['1星', '2星', '3星', '4星', '5星'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: sortedGoods.map(good => good.name),
      axisLabel: {
        interval: 0,
        rotate: 30, // 如果名称太长可以旋转30度
        formatter: function(value) {
          // 名称过长时显示省略号
          if (value.length > 10) {
            return value.substring(0, 8) + '...';
          }
          return value;
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '评价数量'
    },
    series: seriesData
  };

  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}

// 根据评分获取颜色
function getRatingColor(rating) {
  const colors = {
    1: '#ff4d4f', // 红色 - 差评
    2: '#ffa940', // 橙色 - 一般
    3: '#ffc53d', // 黄色 - 中等
    4: '#73d13d', // 绿色 - 良好
    5: '#389e0d'  // 深绿 - 优秀
  }
  return colors[rating] || '#999'
}

// 热销商品TOP10
function initSalesChart() {
  if (!salesChart.value) return;
  const chart = echarts.init(salesChart.value)

  // 按销量排序并取前10
  const sortedGoods = [...goodsData.value]
      .sort((a, b) => b.sales - a.sales)
      .slice(0, 10)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '销量'
    },
    yAxis: {
      type: 'category',
      data: sortedGoods.map(g => g.name),
      name: '商品名称'
    },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: sortedGoods.map(g => g.sales),
        itemStyle: {
          color: function(params) {
            const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'];
            return colorList[params.dataIndex % colorList.length];
          }
        }
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 库存预警分析
function initStockChart() {
  if (!stockChart.value) return;
  const chart = echarts.init(stockChart.value)

  const warningGoods = goodsData.value.filter(g => g.store < 10)
  const normalGoods = goodsData.value.filter(g => g.store >= 10)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: 10,
      left: 'center',
      data: ['库存充足', '库存预警']
    },
    series: [
      {
        name: '库存状态',
        type: 'pie',
        radius: ['40%', '55%'],
        center: ['50%', '40%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        data: [
          { value: normalGoods.length, name: '库存充足', itemStyle: { color: '#91cc75' } },
          { value: warningGoods.length, name: '库存预警', itemStyle: { color: '#ee6666' } }
        ]
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 价格区间分布
function initPriceChart() {
  if (!priceChart.value) return;
  const chart = echarts.init(priceChart.value)

  // 定义价格区间
  const priceRanges = [
    { min: 0, max: 50, name: '0-50元' },
    { min: 50, max: 100, name: '50-100元' },
    { min: 100, max: 200, name: '100-200元' },
    { min: 200, max: 500, name: '200-500元' },
    { min: 500, max: Infinity, name: '500元以上' }
  ]

  // 统计各价格区间商品数量
  const data = priceRanges.map(range => {
    return {
      name: range.name,
      value: goodsData.value.filter(g =>
          g.price >= range.min && g.price < range.max
      ).length
    }
  })

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: data.map(d => d.name)
    },
    series: [
      {
        name: '价格分布',
        type: 'pie',
        radius: '70%',
        center: ['40%', '50%'],
        roseType: 'radius',
        itemStyle: {
          borderRadius: 8
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        data: data
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// // 获取表格数据
// getTableData()
// function getTableData() {
//   get(url.list, params, content => {
//     tableData.value = copy(content)
//     allTableData.value = copy(content)
//   })
// }
</script>

<style lang="scss" scoped>
.wrapper{
  height: auto;
  .util{
    width: 100%;
    height: 50px;
    background-color: #ffffff;
    border-radius: 4px;
    margin-bottom: 20px;
    box-shadow: 2px 2px 10px rgba(0,0,0,0.2);
    display: flex;
    align-items: center;
    .add-button{
      margin-left: 20px;
      margin-right: 809px;
    }
    span{
      font-size: 14px;
      margin-left: 20px;
    }
  }

  // 新增的仪表盘样式
  .dashboard-cards {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;

    .dashboard-card {
      border-radius: 8px;
      overflow: hidden;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: bold;
        font-size: 16px;
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .main{
    width: 100%;
    min-height: 580px;
    padding: 20px;
    background-color: #ffffff;
    border-radius: 4px;
    box-shadow: 2px 0px 10px rgba(0,0,0,0.2);
  }
}

@media (max-width: 1200px) {
  .dashboard-cards {
    grid-template-columns: 1fr !important;
  }
}
</style>